package cc.iteachyou.cms.controller.tools;

import java.util.Map;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cc.iteachyou.cms.common.ResponseResult;
import cc.iteachyou.cms.common.StateCodeEnum;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;

/**
 * Base64
 * @author Jonas
 *
 */
@RestController
@RequestMapping("tools/base64")
public class Base64ToolController {
	
	/**
	 * 格式化Json
	 * @param params
	 * @return
	 */
	@PostMapping("encode")
	public ResponseResult encode(@RequestBody Map<String,String> params) {
		ResponseResult result = null;
		if(!params.containsKey("text") || StrUtil.isBlank(params.get("text"))) {
			result = ResponseResult.Factory.newInstance(Boolean.FALSE, StateCodeEnum.HTTP_SUCCESS.getCode(), null, StateCodeEnum.HTTP_SUCCESS.getDescription());
			return result;
		}
		try {
			String string = Base64.encode(params.get("text"));
			result = ResponseResult.Factory.newInstance(Boolean.TRUE, StateCodeEnum.HTTP_SUCCESS.getCode(), string, StateCodeEnum.HTTP_SUCCESS.getDescription());
			return result;
		} catch (Exception e) {
			result = ResponseResult.Factory.newInstance(Boolean.FALSE, StateCodeEnum.HTTP_SUCCESS.getCode(), null, StateCodeEnum.HTTP_SUCCESS.getDescription());
			return result;
		}
	}
	
	/**
	 * 格式化Json
	 * @param params
	 * @return
	 */
	@PostMapping("decode")
	public ResponseResult decode(@RequestBody Map<String,String> params) {
		ResponseResult result = null;
		if(!params.containsKey("text") || StrUtil.isBlank(params.get("text"))) {
			result = ResponseResult.Factory.newInstance(Boolean.FALSE, StateCodeEnum.HTTP_SUCCESS.getCode(), null, StateCodeEnum.HTTP_SUCCESS.getDescription());
			return result;
		}
		try {
			String string = Base64.decodeStr(params.get("text"));
			result = ResponseResult.Factory.newInstance(Boolean.TRUE, StateCodeEnum.HTTP_SUCCESS.getCode(), string, StateCodeEnum.HTTP_SUCCESS.getDescription());
			return result;
		} catch (Exception e) {
			result = ResponseResult.Factory.newInstance(Boolean.FALSE, StateCodeEnum.HTTP_SUCCESS.getCode(), null, StateCodeEnum.HTTP_SUCCESS.getDescription());
			return result;
		}
	}
}
